package com.loopy.fruns.web;

import com.loopy.fruns.entity.Cart;
import com.loopy.fruns.entity.CartItem;
import com.loopy.fruns.entity.Furn;
import com.loopy.fruns.service.FurnService;
import com.loopy.fruns.service.impl.FurnServiceImpl;
import com.loopy.fruns.utils.DataUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class CartServlet extends BasicServlet {
    private FurnService furnService = new FurnServiceImpl();

    protected void addItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = DataUtils.parseInt(request.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        if(furn==null||furn.getStock()<=0){
            return;
        }

        CartItem item = new CartItem(furn.getId(),furn.getName(),1,furn.getPrice(),furn.getPrice());
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        if (cart==null){
            cart = new Cart();
            request.getSession().setAttribute("cart",cart);
        }
        cart.addItem(item);

        System.out.println("cart="+cart);
       response.sendRedirect(request.getHeader("Referer"));

    }

    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer count = DataUtils.parseInt(req.getParameter("count"), 1);
        Integer id = DataUtils.parseInt(req.getParameter("id"), 0);
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        if(null !=cart){
            cart.updateCount(id,count);
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = DataUtils.parseInt(req.getParameter("id"), 0);
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        if(null !=cart){
            cart.deleteItems(id);
        }
        cart.deleteItems(id);
        resp.sendRedirect(req.getHeader("Referer"));
    }


    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart)req.getSession().getAttribute("cart");
        if(null !=cart){
            cart.clear();
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
